import Taro from "@tarojs/taro";
import { sign, signed } from './../../actions/counter'
import config from '../domian'
import util from './util'
import WxRequest from './../wx-request/index'
import login from './../login'
import store from '../../store/store'

const STATUS_FAIL = 0
const STATUS_SUCCESS = 1
const STATUS_LOGIN = 2
const STATUS_APPLY = 3

const DEFAULT_EXTRA_OPTIONS = {
    showLoading: false,               // 是否显示 loading
    loadingTitle: '处理中 ...',      // loading 标题
    useDefaultErrorHandler: true,    // 是否使用默认错误处理
    needLogin: true,                 // 是否需要登录
    showApplyTips: true              // 是否显示申请提示
}

// 打印调试
function logDebug(data) {
    try {
        console.log(data)
    } catch (e) { }
}

// 默认错误处理
function defaultErrorHandler(tip, err, options) {
    console.log(err)

    if (options.useDefaultErrorHandler) {
        util.Taro.showToast(tip)
    }
}

// 响应成功
function responseSuccess(response) {
    const data = response.data

    if (!data.data) {
        data.data = {}
    }

    data.data.__info = data.info
    return data.data
}

// 响应失败
function responseFail(data, options) {
    console.log(data)

    if (options.useDefaultErrorHandler) {
        util.Taro.showModal(data.info)
    }
}

// 响应需要登录
function responseLogin(response, options) {
    if (options.needLogin) {
        return login(options)
    } else {
        return Promise.reject(response)
    }
}

// 响应需要申请
function responseApply(data, options) {
    if (options.showApplyTips) {
        util.Taro.showModal(`${data.info}\nhrId: ${data.data.hrId}\nuserId: ${data.data.userId}`)
    }
}

// 响应后处理
function handleResponse(response, options) {
    let data = response.data
    let { status } = data
    if (status) {
        switch (status) {
            case -1: //未登录
                {//控制登陆模块
                    // Taro.redirectTo({
                    //     url: '/subPackages/subPackageS/authorize/authorize?type=getPhoneNumber'
                    // })
                    store.dispatch(sign())   //未登录显示登陆模块
                }
                break;
            case 1: //登陆正常
                {
                    // console.log(store.dispatch)
                    // store.dispatch(signed())   //登陆正常隐藏登陆模块
                    // 成功 (返回resolve)
                    if (data.status === STATUS_SUCCESS) {
                        response = responseSuccess(response)
                        return Promise.resolve(response)
                    }

                    // 登录 (返回promise)
                    if (data.status === STATUS_LOGIN) {
                        return responseLogin(response, options)
                    }

                    // 失败 (返回reject)
                    if (data.status === STATUS_FAIL) {
                        responseFail(data, options)
                        return Promise.reject(response)
                    }

                    // 申请 (返回reject)
                    if (data.status === STATUS_APPLY) {
                        responseApply(data, options)
                        return Promise.reject(response)
                    }
                }
                break;
            case 2: //未创建简历
                {//前往创建简历
                    Taro.redirectTo({
                        url: '/subPackages/subPackageS/myResume/myResume'
                    })
                }
                break;
            case 0: //登陆异常请重试
                {
                    util.Taro.showToast(data.info)
                }
                break;
        }
    } else if (status == 0) {
        return Promise.reject(response.data.info)
    }
}

const wxRequest = new WxRequest({
    baseURL: config[process.env.NODE_ENV].hostSaas,
    header: {
        'content-type': 'application/x-www-form-urlencoded'
    }
})
// 添加下载拦截器
wxRequest.interceptors.downloadFile.use(
    (options) => {
        // 合并额外配置
        options = Object.assign({}, DEFAULT_EXTRA_OPTIONS, options)

        // 是否 loading
        if (options.showLoading) {
            util.Taro.showLoading(options.loadingTitle)
        }

        // logDebug.
        logDebug(options)

        return options
    },

    (err) => {
        defaultErrorHandler('请求错误', err, options)
        return Promise.reject(err)
    }
)

// 添加请求拦截器
wxRequest.interceptors.request.use(
    (options) => {
        // 合并额外配置
        options = Object.assign({}, DEFAULT_EXTRA_OPTIONS, options)

        // 是否 loading
        if (options.showLoading) {
            util.Taro.showLoading(options.loadingTitle)
        }
        // 是否需要带上企业id
        let params = {}
        //是否是无需登录信息的接口
        if (options.url.indexOf('/worker/job/show') > -1) {
            params.avoidAuthorization = 'true'
        } else {
            params.Authorization = Taro.getStorageSync('Authorization')
            params.avoidAuthorization = 'false'
        }

        //判断是否登录
        if (Taro.getStorageSync('Authorization')) {
            params.Authorization = Taro.getStorageSync('Authorization')
            params.avoidAuthorization = 'false'
        }

        //是否具有企业资质
        if (Taro.getStorageSync('company')) {
            params.company = Taro.getStorageSync('company') ? Taro.getStorageSync('company') : ''
        }

        //H5带上domain参数
        if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
            params.domain = config[process.env.NODE_ENV].domain
        }

        // header 带 Authorization和sass 地址
        options.header = Object.assign(options.header || {}, params)
        //H5跨域兼容
        options.header.mode = Object.assign('no-cors')

        // options.header.Authorization = 'oV9w_1iNuU0GStiKi-gGmP1pkJVk'

        // logDebug.
        logDebug(options)

        return options
    },

    (err) => {
        defaultErrorHandler('请求错误', err, options)
        return Promise.reject(err)
    }
)

// 添加响应拦截器
wxRequest.interceptors.response.use(
    (response) => {
        const options = response.config

        // hideLoding.
        if (options.showLoading) {
            Taro.hideLoading()
        }
        // 转换数据格式
        if (typeof response === 'string') {
            try {
                response = JSON.parse(response)
            } catch (err) {
                defaultErrorHandler('服务异常', err, options)
                return Promise.reject(err)
            }
        }

        // logDebug.
        logDebug(response)
        return handleResponse(response, options)
    },

    (err) => {
        const options = err.config

        // hideLoding.
        if (options.showLoading) {
            Taro.hideLoading()
        }

        defaultErrorHandler('网络错误', err, options)
        return Promise.reject(err)
    }
)

export default wxRequest